var bWCDebug = false;

var feed_teams = '/qualifiedteams/worldcup/qualified_teams.xml';
var feed_matches = '/matches/worldcup/list_overview.xml';
// debug
var feed_matches_debug = 'http://themadpixelfactory.com/seguimiento_fifa/FIFA_matches0.xml';

var feed_news = '/news/worldcup/teams/team={0}/rss.xml';
var feed_news_fifa = '/news/worldcup/rss.xml';
var feed_news_widgets = '/xmlfeed/widgets/worldcup/team={0}.xml';
var feed_live_match = '/matches/worldcup/live/match={0}/list.xml';

var url_team = '/worldcup/teams/team={0}/index.html';

// debug
var feed_live_match_debug = 'http://themadpixelfactory.com/seguimiento_fifa/ficheros/{0}.xml';

var feed_player = '/worldfootball/statisticsandrecords/players/player={0}/index.html';

var share_facebook = "http://www.facebook.com/sharer.php?u={0}&t={1}";
var share_buzz = "http://www.google.com/buzz/post?message={1}&url={0}";
var share_twitter = "http://twitter.com/home?status={0}+%23chromefifa+%23worldcup";

var url_suffix = 'cid=google_chromeextension';

var flag_pattern_s = 'http://www.fifa.com/imgml/flags/s/{0}.gif';
var flag_pattern_m = 'http://www.fifa.com/imgml/flags/m/{0}.gif';


function addUrlSuffix(strUrl)
{
	if (strUrl.indexOf("?")==-1)
		strUrl += "?" + url_suffix;
	else
		strUrl += "&" + url_suffix;
	return strUrl;	
}

var match_live_events = {
    'START': '',
    'OG': '',
    'G': '',
    'PG': '',
    'STOP': '',
    'PK': ''
};
var match_live_share_events = {
    'OG': '',
    'G': '',
    'PG': '',
    'PK': ''
};

var wcTeams = [];
var wcMacthes = [];
var UILocale = '';
var ExtensionID = '';

//var UITimeZone =(new Date().getTimezoneOffset()/60)*(-1);
var UITimeZone = new Date().toString();

function getUI(strId){
    return chrome.i18n.getMessage(strId);
}

function setTextUI(strId){
    $("span#" + strId).html(chrome.i18n.getMessage(strId));
}

function refreshExtensionIcon(){
    if (isFirstTime()) {
        chrome.browserAction.setBadgeText({
            text: "?"
        });
    }
    else {
        chrome.browserAction.setBadgeText({
            text: ""
        });
        
    }
}

function isFirstTime(){
    var my_team = localStorage['my_team'];
    var follow_my_team = localStorage['follow_my_team'];
    var follow_my_group_teams = localStorage['follow_my_group_teams'];
    var follow_all_teams = localStorage['follow_all_teams'];
    
    var bReturn = false;
    bReturn = (!my_team || !follow_my_team || !follow_my_group_teams || !follow_all_teams);
    return bReturn;
}


function getCacheNumber(){
    var oFecha = new Date();
    strFecha = dateFormat(oFecha, "yyyymmddhhMMss");
    return strFecha;
}

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function(){
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function(val, len){
        val = String(val);
        len = len || 2;
        while (val.length < len) 
            val = "0" + val;
        return val;
    };
    
    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc){
        var dF = dateFormat;
        
        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }
        
        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) 
            throw SyntaxError("invalid date");
        
        mask = String(dF.masks[mask] || mask || dF.masks["default"]);
        
        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }
        
        var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = {
            d: d,
            dd: pad(d),
            ddd: dF.i18n.dayNames[D],
            dddd: dF.i18n.dayNames[D + 7],
            m: m + 1,
            mm: pad(m + 1),
            mmm: dF.i18n.monthNames[m],
            mmmm: dF.i18n.monthNames[m + 12],
            yy: String(y).slice(2),
            yyyy: y,
            h: H % 12 || 12,
            hh: pad(H % 12 || 12),
            H: H,
            HH: pad(H),
            M: M,
            MM: pad(M),
            s: s,
            ss: pad(s),
            l: pad(L, 3),
            L: pad(L > 99 ? Math.round(L / 10) : L),
            t: H < 12 ? "a" : "p",
            tt: H < 12 ? "am" : "pm",
            T: H < 12 ? "A" : "P",
            TT: H < 12 ? "AM" : "PM",
            Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
            o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
            S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
        };
        
        return mask.replace(token, function($0){
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
    monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
};

String.prototype.replaceLatinChar = function(){
	return output = this.replace(/á|é|í|ó|ú|ñ|ä|ë|ï|ö|ü/ig, function(str, offset, s){
		var str = str == "á" ? "a" : str == "é" ? "e" : str == "í" ? "i" : str == "ó" ? "o" : str == "ú" ? "u" : str == "ñ" ? "n" : str;
		str = str == "Á" ? "A" : str == "É" ? "E" : str == "Í" ? "I" : str == "Ó" ? "O" : str == "Ú" ? "U" : str == "Ñ" ? "N" : str;
		str = str == "Á" ? "A" : str == "É" ? "E" : str == "Í" ? "I" : str == "Ó" ? "O" : str == "Ú" ? "U" : str == "Ñ" ? "N" : str;
		str = str == "ä" ? "a" : str == "ë" ? "e" : str == "ï" ? "i" : str == "ö" ? "o" : str == "ü" ? "u" : str;
		str = str == "Ä" ? "A" : str == "Ë" ? "E" : str == "Ï" ? "I" : str == "Ö" ? "O" : str == "Ü" ? "U" : str;
		return (str);
	})
}

// For convenience...
Date.prototype.format = function(mask, utc){
    return dateFormat(this, mask, utc);
};

// String.format 
function _StringFormatInline(){
    var txt = this;
    for (var i = 0; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
        //txt = txt.replace(exp, arguments[i].replace(/((\%3C)|<)((\%2F)|\/)*[a-z0-9\%]+((\%3E)|>)/ig,''));
        txt = txt.replace(exp, arguments[i]);
    }
    return txt;
}

function _StringFormatStatic(){
    for (var i = 1; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        //arguments[0] = arguments[0].replace(exp, arguments[i].replace(/((\%3C)|<)((\%2F)|\/)*[a-z0-9\%]+((\%3E)|>)/ig,''));
        arguments[0] = arguments[0].replace(exp, arguments[i]);
    }
    return arguments[0];
}

if (!String.prototype.format) {
    String.prototype.format = _StringFormatInline;
}

if (!String.format) {
    String.format = _StringFormatStatic;
}


// LocalStorage set/get Object
Storage.prototype.setObject = function(key, value){
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key){
    try {
        return JSON.parse(this.getItem(key));
    } 
    catch (e) {
    
    }
}

// Array indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, fromIndex){
        if (fromIndex == null) {
            fromIndex = 0;
        }
        else 
            if (fromIndex < 0) {
                fromIndex = Math.max(0, this.length + fromIndex);
            }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj) 
                return i;
        }
        return -1;
    };
}


function URLEncode(clearString){
	return encodeURIComponent(clearString);
}

function getLocalDate(strDate){

    if (strDate == "") 
        return "-";
    
    var d = new Date()
    var localOffset = -d.getTimezoneOffset() * 6000;
    var strDateReturn = "";
    var bOnlyDate = false;
    if (strDate.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{1,2}:[0-9]{2}:[0-9]{2}Z$/)) {
        strDate = strDate.split("T").join(" ").split("Z").join("");
    }
    
    if (strDate.match(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/)) {
        bOnlyDate = true;
        var dateWrapper = new Date(strDate);
        if (isNaN(dateWrapper.getDate())) {
            var oDate = strDate.split("/");
            strDate = oDate[1] + "-" + oDate[0] + "-" + oDate[2];
        };
            }
    
    try {
        var now = new Date(strDate);
        d = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes());
        
        var UILocale = chrome.i18n.getMessage("@@ui_locale");
        if ((UILocale == "en") || (UILocale == "en_GB") || (UILocale == "en_US")) {
			switch (UILocale)
			{
				case "en":
					if (bOnlyDate) 
						strDateReturn = dateFormat(d, "yyyy-mm-dd");
	            	else 
						strDateReturn = dateFormat(d, "yyyy-mm-dd HH:MM");
					break;
				case "en_GB":
					if (bOnlyDate) 
						strDateReturn = dateFormat(d, "yyyy-mm-dd");
	            	else 
						strDateReturn = dateFormat(d, "yyyy-mm-dd HH:MM");
					break;				
				case "en_US":
					if (bOnlyDate) 
						strDateReturn = dateFormat(d, "mm/dd/yyyy");
	            	else 
						strDateReturn = dateFormat(d, "mm/dd/yyyy HH:MM");
					break;
			}
			
        }
        else {
            if (bOnlyDate) 
                strDateReturn = dateFormat(d, "dd-mm-yyyy");
            else 
                strDateReturn = dateFormat(d, "dd-mm-yyyy HH:MM");
        }
    } 
    catch (e) {
        strDateReturn = strDate;
    }
    return strDateReturn;
}

// Function to sort JSON arrays
// sample: elements.sort(sort_by('price', true, parseInt));
var sort_by = function(field, reverse, primer){

    reverse = (reverse) ? -1 : 1;
    
    return function(a, b){
    
        a = a[field];
        b = b[field];
        
        if (typeof(primer) != 'undefined') {
            a = primer(a);
            b = primer(b);
        }
        
        if (a < b) 
            return reverse * -1;
        if (a > b) 
            return reverse * 1;
        return 0;
        
    }
}

function showDebug(){
    console.log("follow_my_team:" + localStorage['follow_my_team']);
    console.log("follow_my_group_teams:" + localStorage['follow_my_group_teams']);
    console.log("follow_all_teams:" + localStorage['follow_all_teams']);
    console.log("my_team_group_id:" + localStorage['my_team_group_id']);
    console.log("my_team_group_name:" + localStorage['my_team_group_name']);
    console.log("my_team" + localStorage['my_team']);
    var obj = localStorage.getObject('wcSelectedMatches');
    console.log("selectedMatches:" + JSON.stringify(obj));
    console.log("selectedLiveMatches 2:" + localStorage['wcSelectedLiveMatches']);
}

// "select team", "ESP"
function trackEvent(strIdEvent, strIdText){
    try {
		if (!bWCDebug)
			strIdText = strIdText.split(" v ").join(" - ");
			strIdText = strIdText.split(" vs ").join(" - ");
			strIdText = strIdText.split(" x ").join(" - ");		 
        	_gaq.push(['_trackEvent', strIdEvent, strIdText]);
    } 
    catch (e) {
    
    }
}

var doit = function(b){
    function c(){
        for (var l = 0, m = 0; m < arguments.length; m++) 
            l = l + arguments[m] & 4294967295;
        return l
    }
    function d(l){
        l = l = String(l > 0 ? l : l + 4294967296);
        var m;
        m = l;
        for (var o = 0, n = false, p = m.length - 1; p >= 0; --p) {
            var q = Number(m.charAt(p));
            if (n) {
                q *= 2;
                o += Math.floor(q / 10) + q % 10
            }
            else 
                o += q;
            n = !n
        }
        m = m = o % 10;
        o = 0;
        if (m != 0) {
            o = 10 - m;
            if (l.length % 2 == 1) {
                if (o % 2 == 1) 
                    o += 9;
                o /= 2
            }
        }
        m = String(o);
        m += l;
        return l = m
    }
    function e(l){
        for (var m = 5381, o = 0; o < l.length; o++) 
            m = c(m << 5, m, l.charCodeAt(o));
        return m
    }
    function f(l){
        for (var m = 0, o = 0; o < l.length; o++) 
            m = c(l.charCodeAt(o), m << 6, m << 16, -m);
        return m
    }
    var g = "au";
    g += "th";
    g += "_";
    g += "to";
    g += "k";
    g += "en";
    var i = e(b);
    i = i >> 2 & 1073741823;
    i = i >> 4 & 67108800 | i & 63;
    i = i >> 4 & 4193280 | i & 1023;
    i = i >> 4 & 245760 | i & 16383;
    var j = "7";
    h = f(b);
    var k = (i >> 2 & 15) << 4 | h & 15;
    k |= (i >> 6 & 15) << 12 | (h >> 8 & 15) << 8;
    k |= (i >> 10 & 15) << 20 | (h >> 16 & 15) << 16;
    k |= (i >> 14 & 15) << 28 | (h >> 24 & 15) << 24;
    j += d(k);
    i = "";
    i += j;
    return i
};
